package org.goose.web;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.goose.web.controllers.OrderController;
import org.goose.web.templates.TemplateFactory;

public class HospitalityHandler extends AbstractHandler {
	private final static Logger logger = Logger
			.getLogger(HospitalityHandler.class);
	
	public void handle(String target, Request baseRequest,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		// 0. Initialize Response
		response.setContentType("text/html;charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);

		// 1. Determine request-method
		int method = 0;
		switch (request.getMethod().toString()) {
		case "POST":
			method = 1;
			break;
		case "GET":
			method = 2;
			break;
		case "PUT":
			method = 3;
			break;
		case "DELETE":
			method = 4;
			break;
		}
		logger.info("Request Method: " + request.getMethod());

		// 2. Determine request-path
		String path = request.getPathInfo();
		logger.info("Request Path: " + path);

		// 3. Invoke handler
		Map<String, String> pathVariables = new HashMap<String, String>(); // Gets
																			// filled
																			// with
																			// the
																			// available
																			// path-variables.
		org.goose.web.Handler handler = HandlerMap.getHandler(path, method,
				pathVariables);
		VelocityContext context = new VelocityContext();
		String t = null;
		String rawT = null;
		if (handler != null) {
			rawT = handler.invoke(request, context, pathVariables);
			t = "src/main/resources/velocity/"
					+ rawT;
			baseRequest.setHandled(true);
		} else {
			baseRequest.setHandled(false);
			return;
		}

		// 4. If Prefixed
		System.out.println(rawT);
		if (rawT.contains(":")) {
			String _prefix = rawT.split(":")[0];
			String _value = rawT.split(":")[1];
			switch (_prefix) {
			case "redirect":
				logger.info("Returning redirect:"+_value);
				response.sendRedirect(_value);
				return;
			case "raw":
				logger.info("Returning raw:"+_value);
				response.getWriter().println(_value);
				return;
			}
		}

		// 5. Merge Template
		Velocity.init();

		System.out.println(t);
		context.put("content", t);
		StringWriter sw = new StringWriter();
		Template layout = TemplateFactory.getTemplate("layout.vm");
		layout.merge(context, sw);

		// 6. Respond
		response.getWriter().println(sw);

	}

	public static void main(String[] args) throws Exception {
		// -1. Logger config
		BasicConfigurator.configure();
		logger.info("Hospitality© started on port 30490");
		
		// 0. Initialize RequestMap
		HandlerMap.init();

		// 1. Create Server
		Server server = new Server(30490);
		server.setHandler(new HospitalityHandler());

		// 2. Create ResourceHandler
		ResourceHandler resource_handler = new ResourceHandler();
		resource_handler.setDirectoriesListed(true);
		resource_handler.setWelcomeFiles(new String[] { "index.html" });
		resource_handler.setResourceBase("src/main/resources");

		// 3. Create Application Handler
		HospitalityHandler settlement_handler = new HospitalityHandler();
		LoginHandler loginHandler = new LoginHandler();

		// 4. Add Handlers to Server
		HandlerList handlers = new HandlerList();
		handlers.setHandlers(new Handler[] { resource_handler,
				loginHandler,
				settlement_handler });
		server.setHandler(handlers);

		// 5. Start Server
		server.start();
		server.join();
	}
}
